package shuaige.jdk.多线程.base.线程的创建和启动.Callable接口;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class 实现Callable接口创建线程类2 implements Callable<Integer> {
    int number;

    public 实现Callable接口创建线程类2(int number) {
        this.number = number;
    }

    public static void main(String[] args) {
        实现Callable接口创建线程类2 tt = new 实现Callable接口创建线程类2(3);
        FutureTask<Integer> task = new FutureTask<>(tt);
        // 启动线程
        new Thread(task, "有返回值的线程").start();
        // 获取返回值
        try {
            System.out.println(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer call() throws InvalidParamaterException {
        int fact = 1;
        if (number < 0) {
            throw new InvalidParamaterException("Number must be positive");
        }

        for (int count = number; count > 1; count--) {
            System.out.println("fact:" + fact + " * count:" + count);
            fact = fact * count;
        }

        return fact;
    }

    private class InvalidParamaterException extends Exception {
        public InvalidParamaterException(String message) {
            super(message);
        }
    }
}